﻿using FluentValidation;
using FluentValidation.Results;
using SXICE.Core.Domains;
using SXICE.Core.Models;
using SXICE.Core.Models.Search;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace SXICE.Service.Utilities
{
    /// <summary>
    /// 帮助扩展类
    /// </summary>
    public static class HelperExtentions
    {
        /// <summary>
        /// 拼接错误
        /// </summary>
        /// <param name="errors">要拼接的错误</param>
        /// <returns>结果</returns>
        public static string JoinErrors(this IList<ValidationFailure> errors)
        {
            return string.Join("\n", errors.Select(err => err.ErrorMessage));
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="validator">验证器</param>
        /// <param name="instance">要验证的对象</param>
        /// <param name="errors">错误信息</param>
        /// <returns>验证结果</returns>
        public static bool Validate<T>(this AbstractValidator<T> validator, T instance, out string errors)
        {
            return Validate(validator, instance, out errors, null);
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="validator">验证器</param>
        /// <param name="instance">要验证的对象</param>
        /// <param name="errors">错误信息</param>
        /// <param name="properties">要验证的属性</param>
        /// <returns>验证结果</returns>
        public static bool Validate<T>(this AbstractValidator<T> validator, T instance, out string errors, params string[] properties)
        {
            errors = null;
            var result = null == properties ? validator.Validate(instance) : validator.Validate(instance, properties);
            if (!result.IsValid)
                errors = result.Errors.JoinErrors();
            return result.IsValid;
        }

        /// <summary>
        /// 转换为数字Result
        /// </summary>
        /// <param name="returnResult">要转换的ReturnResult对象</param>
        /// <returns>结果</returns>
        public static ReturnResult<int> ToIntResult<T>(this ReturnResult<T> returnResult) where T : BaseDomain
        {
            if (returnResult.Success)
                return new ReturnResult<int>(returnResult.Result.Id);
            return new ReturnResult<int>(returnResult.ErrorCode, returnResult.ErrorMessage);
        }
    }
}
